//
//  YCLEmoticonManager.swift
//  02.表情键盘
//
//  Created by yaochunlin on 16/4/25.
//  Copyright © 2016年 yaochunlin. All rights reserved.
//

/// 一页显示20个表情模型
let YCLEmoticonNumberOfPage = 20

/// 一页7列
let YCLEmoticonColumnOfPage = 7

/// 一页3行
let YCLEmoticonRowOfPage = 3

// bundle的路径
let EmoticonsBundlePath = NSBundle.mainBundle().pathForResource("Emoticons", ofType: "bundle")!

import UIKit

class YCLEmoticonManager: NSObject {
    
    //沙盒路径
    private let emoticonPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/emoticons.plist"

    //单例
    static let shareEmoticonManager:YCLEmoticonManager = YCLEmoticonManager()
    
    //懒加载，这样只会加载一次所有表情包
    lazy var allPackages: [YCLEmoticonPackageMode] = self.loadAllEmoticonPackages()
    
    //加载所有表情包
    private func loadAllEmoticonPackages() ->[YCLEmoticonPackageMode] {
    
        //最近表情包
        let recentPackage = YCLEmoticonPackageMode.init(id: "", group_name_cn: "最近", emoticons: loadRecentEmoticons())
        //默认表情包
        let defaultPackage = loadEmoticonPackage("com.sina.default")
        let emojiPackage = loadEmoticonPackage("com.apple.emoji")
        let lxhPackage = loadEmoticonPackage("com.sina.lxh")
        
        return [recentPackage, defaultPackage, emojiPackage, lxhPackage]
    }
    
    //加载表情包模型
    //bundle路径
    
    
    /*!
     
     - parameter id: 表情包文件夹名称
     
     - returns: 表情包模型
     */
    private func loadEmoticonPackage(id: String) -> YCLEmoticonPackageMode {
    
        //获得全路径
        let allPath = "\(EmoticonsBundlePath)/\(id)/info.plist"
//        print("全路径:\(allPath)")
        
        //加载plist文件
        let dict = NSDictionary.init(contentsOfFile: allPath)!
        
        let group_name_cn = dict["group_name_cn"] as! String
        
        let emoticonsArr = dict["emoticons"] as! [[String: String]]
        
        //创建模型数组
        var emoticons = [YCLEmoticonModel]()
        
        for dict in emoticonsArr {
            
            //字典转模型
            let emoticon = YCLEmoticonModel.init(dict: dict, id: id)
            
            emoticons.append(emoticon)
        }
        
        //创建表情包模型
        let packageModel = YCLEmoticonPackageMode.init(id: id, group_name_cn: group_name_cn, emoticons: emoticons)
        
//        print("packageModel:\(packageModel)")
        
        return packageModel
        
    }
    
    //添加表情模型到最近表情包
    func addFavorate(emoticon: YCLEmoticonModel) {
        
        //获取最近使用表情
        var recentPageEmoticons = allPackages[0].pageEmoticons[0]
        
        //判断是否有重复的表情
        var sameEmoticon: YCLEmoticonModel?
        for e in recentPageEmoticons {
            
            if (emoticon.emoji != nil && emoticon.code == e.code) || (emoticon.chs != nil && emoticon.chs == e.chs) {
                
                sameEmoticon = e
                
                break
            }
        }
        
        if let e = sameEmoticon {
            
            //删除重复的表情
            let index = recentPageEmoticons.indexOf(e)
            
            recentPageEmoticons.removeAtIndex(index!)
        }
        
        //赋值在最前面
        recentPageEmoticons.insert(emoticon, atIndex: 0)
        
        //当模型大于20个时删除后面的
        while recentPageEmoticons.count > YCLEmoticonNumberOfPage {
            
            recentPageEmoticons.removeLast()
        }
        
        //需要重新赋值回来
        allPackages[0].pageEmoticons[0] = recentPageEmoticons
        
//        print("最近表情1: \(recentPageEmoticons)")
//        print("最近表情2: \(allPackages[0].pageEmoticons[0])")
        
        //保存到本地
        saveRecentEmoticons()
        
    }
    
    //保存最近表情
    private func saveRecentEmoticons() {
    
        //归档
        NSKeyedArchiver.archiveRootObject(allPackages[0].pageEmoticons[0], toFile: emoticonPath)
    }
    
    //从沙盒加载
    private func loadRecentEmoticons() -> [YCLEmoticonModel] {
    
        //解档
        if let emoticons = NSKeyedUnarchiver.unarchiveObjectWithFile(emoticonPath) as? [YCLEmoticonModel] {
        
            return emoticons
        }else{
        
            return [YCLEmoticonModel]()
        }
        
    }
    
    
}
